<template>
	<view class="customPage">
		<view class="cellList avatarBox">
			<view class="subTitle">头像</view>
			<view class="content">
				<image class="avatar" :src="info.avatar" mode="" @click="changeAvatar"></image>
			</view>
		</view>
		<view class="cellList">
			<view class="subTitle">昵称</view>
			<input type="text" placeholder="请输入昵称" placeholder-class="holder" class="content" v-model="info.nickname" />
		</view>
		<view class="cellList">
			<view class="subTitle">姓名</view>
			<input type="text" placeholder="请输入姓名" placeholder-class="holder" class="content" v-model="info.real_name" />
		</view>
		<view class="cellList">
			<view class="subTitle">电话<text>（不可修改）</text></view>
			<input type="text" placeholder="请输入电话" placeholder-class="holder" class="content" v-model="info.mobile" disabled />
		</view>
		<view class="cellList">
			<view class="subTitle">电子邮箱</view>
			<input type="text" placeholder="请输入电子邮箱" placeholder-class="holder" class="content" v-model="info.email" />
		</view>
		<view class="cellList" @click="showDate = true">
			<view class="subTitle">生日</view>
			<input type="text" placeholder="请选择生日" placeholder-class="holder" class="content" v-model="info.birthday" disabled />
			<u-icon name="arrow-right" color="#333333" size="24"></u-icon>
		</view>
		<view class="cellList noBorder" @click="chooseSex">
			<view class="subTitle">性别</view>
			<input type="text" placeholder="请选择性别" placeholder-class="holder" class="content" v-model="sex" disabled />
			<u-icon name="arrow-right" color="#333333" size="24"></u-icon>
		</view>
		<!-- <view class="cellList m noBorder" @click="toCode">
			<view class="subTitle">我的名片</view>
			<view class="content">
				<image class="icon" src="/static/member_icon/icon2.png" mode="widthFix"></image>
			</view>
			<u-icon name="arrow-right" color="#333333" size="24"></u-icon>
		</view> -->
		<view class="cellList m noBorder" @click="showArea = true">
			<view class="subTitle">请选择地址</view>
			<input type="text" placeholder="请选择地址" placeholder-class="holder" class="content" v-model="city" disabled />
			<u-icon name="arrow-right" color="#333333" size="24"></u-icon>
		</view>
		<view class="cellList btnItem" @click="logOut">
			<view class="subBtn">退出登陆</view>
		</view>
		<view class="cellList btnItem noBorder" @click="startOut">
			<view class="subBtn">账户注销</view>
		</view>
		<view class="submitBox">
			<button :class="{active: !highLight}" @click="submitFun">保存</button>
		</view>
		<u-picker
			mode="time"
			v-model="showDate"
			:default-time="defaultTime"
			@confirm="timeConfirm"
			@cancel="showDate = false"
		>
		</u-picker>
		<u-popup v-model="showArea" mode="bottom">
			<view>
				<address-picker @onCancel="showArea = false" @onConfirm="areaConfirm" :lists="citys" :idData="defaultArea"></address-picker>
			</view>
		</u-popup>
		<u-popup v-model="showOut" border-radius="30" mode="center" width="80%" :mask-close-able="false">
			<view class="confirmModal">
				<view class="title">您确定要注销账户么?</view>
				<view class="content">如果注销账号，积分将清空</view>
				<view class="btnGroup">
					<button @click="outCancel">取消</button>
					<button :class="{ active: !time }" @click="outConfirm">
						确认注销
						<block v-if="time">
							({{ time }}s)
						</block>
					</button>
				</view>
			</view>
		</u-popup>
<!-- 		<u-modal
			v-model="showOut"
			title="您确定要注销账户么?"
			content="如果注销账号，积分将清空"
			showCancelButton
			async-close
			:confirmText="confirmText"
			@cancel="outCancel"
			@confirm="outConfirm"
		></u-modal> -->
	</view>
</template>

<script>
	import addressPicker from '@/components/addressPicker/addressPicker'
	let timer = null
	export default {
		components:{
			addressPicker
		},
		data() {
			return {
				showOut: false, // 是否展示注销账号弹窗
				time: 5, // 
				info: {}, // 详情
				oinfo: {}, // 初始数据
				sex: '', // 性别
				showDate: false, // 是否展示日期选择器 
				defaultTime: '', // 默认日期
				showArea: false, // 是否展示地区选择器
				citys: [], // 城市数据
				city: '', // 选中的城市
				hashObj: {
					'real_name': '请输入姓名',
					'avatar': '请上传头像',
					'nickname': '请输入电子邮箱',
					'birthday': '请选择生日',
					'sex': '请选择性别',
					'city': '请选择地址',
				},
				defaultArea: [], // 默认地区
				confirmText: '确认注销(5s)',
			}
		},
		methods: {
			areaConfirm(e){
				console.log(e);
				const {
					id,
					name,
				} = e
				this.city = name
				this.info.city = id.join(',')
				this.showArea = false
			},
			getAllCity(){ //获取省市区
				this.$u.api.getAllCityApi({}).then(res=>{
					if(res.code==1){
						this.citys = res.data;
					}
				});
			},
			// 前往我的名片
			toCode: function () {
				const { target_grade, current_grade, target_grade_name } = this.info
				if (current_grade < target_grade) {
					uni.showToast({
						title: `达到${target_grade_name}等级可以绑定亲友`,
						icon: 'none',
					})
					return
				}
				this.$gourl('/pageMember/tarbar/myCode')
			},
			// 提交
			submitFun: function () {
				const {
					highLight,
					info,
					oinfo,
					hashObj,
				} = this
				if (highLight) return
				console.log(info)
				for (let item in info) {
					console.log(item)
					if (!info[item] && oinfo[item]) {
						console.error(item)
						uni.showToast({
							title: hashObj[item],
							icon: 'none'
						})
						return
					}
				}
				this.$u.api.changeUserInfoApi(info).then(res=>{
					const {
						code,
						data,
						message,
					} = res
					if(code == 1){
						uni.showModal({
							title: '提交成功',
							showCancel: false,
						})
					} else {
						uni.showToast({
							title: message || '提交失败',
							icon: 'none'
						})
					}
				})
			},
			// 注销账号
			startOut: function () {
				timer = setInterval(() => {
					if (this.time > 0) {
						this.time --
					} else {
						clearInterval(timer)
						timer = null
					}
				}, 1000)
				this.showOut = true
			},
			// 确认
			outConfirm: async function () {
				const {
					time,
				} = this
				console.log(time)
				if (time) return
				this.showOut = false
				this.$u.api.logoutUserApi().then(res=>{
					const {
						code,
						data,
						message,
					} = res
					if(code == 1){
						this.outSuccess('注销成功')
					} else {
						uni.showToast({
							title: message || '注销失败',
							icon: 'none'
						})
					}
				})
			},
			// 取消
			outCancel: function () {
				timer && clearInterval(timer)
				this.showOut = false
				setTimeout(() => {
					this.time = 5
				}, 300)
			},
			// 跳转到首页
			outSuccess: function (title) {
				uni.removeStorage({
					key:'isLogin',
				})
				uni.removeStorage({
					key:'token',
				})
				uni.removeStorage({
					key:'userInfo',
				})
				uni.showModal({
					title,
					showCancel: false,
					success: () => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				})
			},
			// 退出登陆
			logOut: function () {
				uni.showModal({
					title: '您确定要退出登陆么？',
					success: res => {
						if (res.confirm) {
							this.outSuccess('退出登陆成功')
						}
					}
				})
			},
			// 上传头像
			changeAvatar: function () {
				this.$uploadPic(1, res => {
					const {
						path,
					} = res[0]
					this.info.avatar = path
				})
			},
			// 选择性别
			chooseSex: function () {
				const itemList = ['男', '女']
				uni.showActionSheet({
					itemList,
					success: res => {
						console.log(res)
						const {
							tapIndex,
						} = res
						this.info.sex = tapIndex? '2' : '1'
						this.sex = itemList[tapIndex]
					}
				})
			},
			// 获取用户信息
			getUserInfo: function () {
				this.$u.api.userInfosApi().then(res=>{
					const {
						code,
						data,
						message,
					} = res
					if(code == 1){
						this.info = data
						this.oinfo = JSON.parse(JSON.stringify(data))
						this.sex = data.sex == 1? '男' : '女'
						console.log(data)
						this.defaultArea = data.city? data.city.split(',') : []
					} else {
						uni.showToast({
							title: message || '获取用户信息失败',
							icon: 'none'
						})
					}
				})
			},
			// 获取页面信息
			getInfo: function () {
				uni.showLoading({
					title: '加载中',
				})
				Promise.all([this.$u.api.userInfosApi(), this.$u.api.getAllCityApi()]).then(([info, city]) => {
					if (info.code == 1) {
						this.info = info.data
						this.oinfo = JSON.parse(JSON.stringify(info.data))
						this.sex = info.data.sex == 1? '男' : info.data.sex == 2? '女' : ''
						this.defaultTime = info.data.birthday || this.getTimeDate(+new Date())
						console.log(this.citys)
						if (info.data.city) {
							const defaultArea = info.data.city.split(',') 
							this.defaultArea = defaultArea
							this.$nextTick(() => {
								const provincesItem = city.data.find(item => item.id == defaultArea[0]),
									  cityItem = provincesItem.children.find(item => item.id == defaultArea[1]),
									  countryItem = cityItem.children.find(item => item.id == defaultArea[2])
								this.city = `${provincesItem.name}/${cityItem.name}/${countryItem.name}`
							})
						}
					} else {
						uni.showToast({
							title: info.message || '获取用户信息失败',
							icon: 'none'
						})
					}
					if (city.code == 1) {
						this.citys = city.data
					} else {
						uni.showToast({
							title: city.message || '获取城市信息失败',
							icon: 'none'
						})
					}
				})
				.finally(() => {
					this.$nextTick(() => {
						uni.hideLoading()
					})
				})
			},
			// 时间确认
			timeConfirm: function (val) {
				console.log(val)
				const {
					year,
					month,
					day,
				} = val
				this.info.birthday = `${year}-${month}-${day}`
				this.defaultTime = `${year}-${month}-${day}`
			},
			// 获取日期
			getTimeDate: function (time) {
				time = new Date(time)
				const year = time.getFullYear()
				const month = time.getMonth() + 1
				const date = time.getDate()
				const fullMonth = month < 10 ? `0${month}` : month
				const fullDate = date < 10 ? `0${date}` : date
				// let hour   = (time.getHours()   < 10 ? '0'+ time.getHours()   : time.getHours()).toString()
				// let min    = (time.getMinutes() < 10 ? '0'+ time.getMinutes() : time.getMinutes()).toString()
				// let second = (time.getSeconds() < 10 ? '0'+ time.getSeconds() : time.getSeconds()).toString()
				return `${year}-${fullMonth}-${fullDate}`
			},
		},
		onLoad: function () {
			this.getInfo()
		},
		computed: {
			highLight: function () {
				const {
					info,
					oinfo,
				} = this
				return JSON.stringify(info) == JSON.stringify(oinfo)
			},
		},
	}
</script>

<style>
	page{
		background: #F8F8F8;
	}
</style>
<style lang="scss" scoped>
	.customPage{
		padding-bottom: calc(140rpx + env(safe-area-inset-bottom) / 2);
		.cellList{
			background: white;
			padding: 30rpx;
			display: flex;
			align-items: center;
			border-bottom: 1rpx solid #E9E9E9;
			.subTitle{
				font-size: 30rpx;
				color: #666666;
				text{
					font-size: 26rpx;
				}
			}
			.content{
				flex: 1;
				font-size: 30rpx;
				text-align: right;
				.avatar{
					width: 116rpx;
					height: 116rpx;
					border-radius: 50%;
				}
				.icon{
					width: 28rpx;
					height: 28rpx;
				}
			}
			.holder{
				color: #999999;
			}
			/deep/ .u-icon__icon{
				margin: 0 0 0 36rpx;
			}
		}
		.cellList.m{
			margin: 18rpx 0;
		}
		.noBorder{
			border: none;
		}
		.cellList.avatarBox{
			padding-top: 15rpx;
			padding-bottom: 15rpx;
		}
		.cellList.btnItem{
			justify-content: center;
			.subBtn{
				
			}
		}
		.submitBox{
			background: white;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 10;
			padding: 20rpx 30rpx calc(20rpx + env(safe-area-inset-bottom) / 2) 30rpx;
			button{
				height: 100rpx;
				line-height: 100rpx;
				background: #CCCCCC;
				color: white;
				font-size: 30rpx;
				border: none;
				border-radius: 0;
				border: none;
				&:after{
					content: '';
					border: none;
					border-radius: 0;
				}
			}
			.active{
				background: black;
			}
		}
		.confirmModal{
			border-radius: 30rpx;
			overflow: hidden;
			text-align: center;
			.title{
				font-weight: bolder;
				font-size: 34rpx;
				padding: 60rpx 30rpx 0 30rpx;
			}
			.content{
				padding: 0 30rpx;
				margin: 40rpx 0 60rpx 0;
				font-size: 30rpx;
				color: #7f7f7f;
			}
			.btnGroup{
				display: flex;
				align-items: center;
				border-top: 1px solid #f8f8f8;
				button{
					flex: 1;
					border: none;
					border-radius: 0;
					background: transparent;
					font-size: 32rpx;
					font-weight: bolder;
					height: 100rpx;
					line-height: 100rpx;
					&:first-child{
						border-right: 1px solid #f8f8f8;
					}
					&:last-child{
						color: #7f7f7f;
					}
					&::after{
						border: none;
						border-radius: 0;
					}
				}
				.active{
					color: #576b95 !important;
				}
			}
		}
	}
</style>
